package com.ly.mp.busicen.rule.field.validator.plugin;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.ly.mp.busicen.rule.field.validator.IValidData;
import com.ly.mp.busicen.rule.field.validator.IValidation;
import com.ly.mp.busicen.rule.field.validator.ValidMsg;
import com.ly.mp.busicen.rule.field.validator.ValidatorBase;

/**
 * <rang>(10.2,200.4)[]
 * 
 * @author ly-liuweisong
 *
 */
@Component
public class FieldNumber2Valid extends ValidatorBase {

	@Override
	public String validName() {
		return "number2";
	}

	@Override
	public boolean valid(IValidData validData, IValidation validation) {
		Object value= validData.value();
		if (!StringUtils.isEmpty(value)) {
			if (!RegexUtil.match(RegexUtil.Number, value.toString())) {
				return false;
			}
			String param = validation.strParam();
			if (!StringUtils.isEmpty(param)) {
				String[] mm = param.split(",");
				Double v = Double.parseDouble(value.toString());
				if(mm.length==1) {
					if(param.startsWith(",")) {						
						return v > min("") && v < max(mm[0]);
					}else {
						return v > min(mm[0]) && v < max("");
					}
				}
				if (mm.length == 2) {
					return v > min(mm[0]) && v < max(mm[1]);
				}
			}

		}
		return true;
	}

	private Double min(String min) {
		if (StringUtils.isEmpty(min)) {
			return Double.MIN_VALUE;
		}
		return Double.parseDouble(min);
	}

	private Double max(String max) {
		if (StringUtils.isEmpty(max)) {
			return Double.MAX_VALUE;
		}
		return Double.parseDouble(max);
	}

	@Override
	public ValidMsg errorMsg(IValidation validation) {
		ValidMsg validMsg = super.errorMsg(validation);
		
				
		String[] params = validation.strParam().split(",");
		if(params.length==2&&StringUtils.isEmpty(params[0])) {
			validMsg.setMsg("COM-V-"+validName()+"lt");
			String[] paramt = new String[1];
			paramt[0] = params[1];
			validMsg.setParams(paramt);
			return validMsg;
		}
		validMsg.setParams(params);
		if(params.length==1) {
			if(validation.strParam().startsWith(",")) {						
				validMsg.setMsg("COM-V-"+validName()+"lt");
			}else {
				validMsg.setMsg("COM-V-"+validName()+"gt");
			}
		}
		if (!StringUtils.isEmpty(validation.strMsg())) {
			validMsg.setMsg(validation.strMsg());
		}
		return validMsg;
	}
	

}
